package com.hohode.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;

public class Wcommon {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat simpleDayFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static String nowStr(){
        return simpleDateFormat.format(new Date());
    }

    public static String todayStr(){
        return simpleDayFormat.format(new Date());
    }

    public static boolean isEmpty(String line){
        return line == null || line.length() == 0;
    }

    public static boolean isNotEmpty(String line){
        return !isEmpty(line);
    }

    public static <T> boolean isEmpty(Collection<T> collection){
        return collection == null || collection.isEmpty();
    }

    public static <T> boolean isNotEmpty(Collection<T> collection){
        return !isEmpty(collection);
    }

    private static String LOCALHOST;

    private static InetAddress getInetAddress(){
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                if (iface.isLoopback() || !iface.isUp()) {
                    continue;
                }

                Enumeration<InetAddress> addresses = iface.getInetAddresses();
                while(addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    return addr;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getHostName(){
        InetAddress  address = getInetAddress();
        if(address == null){
            return null;
        }else{
            return address.getHostName();
        }
    }

    public static String getHostIp(){
        InetAddress  address = getInetAddress();
        if(address == null){
            return null;
        }else{
            return address.getHostAddress();
        }
    }

    public static String getHost(){
        if(LOCALHOST != null){
            return LOCALHOST;
        }
        InetAddress  address = getInetAddress();
        if(address == null){
            return null;
        }else{
            LOCALHOST = getHostName()+"["+getHostIp()+"]";
            return LOCALHOST;
        }
    }

    public static String formatDateTime(Date date){
        return simpleDateFormat.format(date);
    }

    public static String formatDay(Date date){
        return simpleDayFormat.format(date);
    }
}
